#include "dingdanexchangewidget.h"
#include "ui_dingdanexchangewidget.h"
#include "readonlydelegate.h"

DingdanExchangeWidget::DingdanExchangeWidget(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DingdanExchangeWidget)
{
    ui->setupUi(this);

    setWindowTitle("单据转换");
    newProductWidget.setWidgetType(SubmitProductWidget::NewProductWidget);

    dingdan = new Dingdan();
    sourceDetail = nullptr;
    sourceProduct = nullptr;
    targetDetail = nullptr;
    targetProduct = nullptr;
    relation = nullptr;
    currentRow = -1;
    type = 0;

    modelSource = new DingdanExchangeStandardItemModel();
    modelTarget = new DingdanExchangeStandardItemModel();
    ui->tableViewSource->setModel(modelSource);
    ui->tableViewTarget->setModel(modelTarget);
    ui->tableViewSource->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableViewSource->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableViewTarget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableViewTarget->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableViewTarget->setSelectionBehavior(QAbstractItemView::SelectRows);

    for(int i=0;i<3;i++){
        ui->tableViewSource->setItemDelegateForColumn(i, new ReadOnlyDelegate());
    }

    connect(ui->tableViewSource, &QTableView::clicked,
            [=](const QModelIndex index)
    {
        currentRow = index.row();
        ui->tableViewTarget->selectRow(index.row());
        setSelectedProduct(index.row());
    });

    connect(ui->tableViewTarget, &QTableView::clicked,
            [=](const QModelIndex index)
    {
        currentRow = index.row();
        ui->tableViewSource->selectRow(index.row());
        setSelectedProduct(index.row());
    });

    connect(ui->tableViewSource, &QTableView::doubleClicked,
            [=](const QModelIndex index)
    {
        currentRow = index.row();
        productPicker.showAndInit();
    });

    connect(ui->tableViewTarget, &QTableView::doubleClicked,
            [=](const QModelIndex index)
    {
        currentRow = index.row();
        productPicker.showAndInit();
    });

    connect(modelSource, &DingdanExchangeStandardItemModel::updateItemCount,
            [=](int count)
    {
        ui->lineEditSourceCount->setText(QString("%1").arg(count));
    });

    ui->dateEdit->setDate(QDate::currentDate());
    ui->dateEdit->setDisplayFormat("yyyy-MM-dd");
    ui->comboBoxTicket->setEnabled(false);

    connect(&dingdanService, &DingdanService::getImportDingdanDetailSuccess,
            [=](
            QList<DingdanDetail*> sourceDetails,
            QList<DingdanDetail*> targetDetails,
            QList<Product*> sourceProducts,
            QList<Product*> targetProducts)
    {
        modelSource->reset();
        modelTarget->reset();
        modelSource->insertItem(sourceDetails, sourceProducts);
        modelTarget->insertItem(targetDetails, targetProducts);
    });

    productPicker.setSelectionMode(QAbstractItemView::SingleSelection);

    connect(ui->lineEditSourceType, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        productPicker.showAndInit();
    });

    connect(ui->lineEditSourceName, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        productPicker.showAndInit();
    });

    connect(ui->lineEditSourceUnit, &ClickedLineEdit::doubleClicked,
            [=]()
    {
        productPicker.showAndInit();
    });

    connect(&productPicker, &ProductPicker::singleSelected,
            [=](Product *product)
    {
        ui->lineEditSourceType->setText(product->type);
        ui->lineEditSourceName->setText(product->name);
        ui->lineEditSourceUnit->setText(product->unit);
        ui->lineEditSourceCount->setText(targetDetail==nullptr?"1":QString("%1").arg(targetDetail->count));
        sourceProduct = product;
        if(sourceDetail == nullptr){
            sourceDetail = new DingdanDetail();
        }
        sourceDetail->productId = sourceProduct->productId;
        sourceDetail->count = targetDetail==nullptr?1:targetDetail->count;
        if(currentRow!=-1){
            modelSource->setItemForRow(currentRow, sourceDetail, sourceProduct);
        }

        ui->tableViewSource->selectRow(currentRow);
    });
}

DingdanExchangeWidget::~DingdanExchangeWidget()
{
    delete ui;
}

void DingdanExchangeWidget::showWithDingdan(Dingdan *dingdan){
    this->dingdan->sourceUsername = dingdan->targetUsername;
    this->dingdan->sourceCompanyId = dingdan->targetCompanyId;
    this->dingdan->targetUsername = dingdan->sourceUsername;
    this->dingdan->targetCompanyId = dingdan->sourceCompanyId;
    this->dingdan->relatedDingdanId = dingdan->dingdanId;
    this->dingdan->sourceFreightUnpaid = dingdan->targetFreightPaid;
    this->dingdan->targetFreightPaid = dingdan->sourceFreightUnpaid;
    this->dingdan->freeTicket = dingdan->freeTicket;
    this->dingdan->freeMoney = dingdan->freeMoney;
    this->dingdan->ticket = dingdan->ticket;
    this->dingdan->money = dingdan->money;
    this->dingdan->isTicket = dingdan->isTicket;

    if(dingdan->type == Dingdan::PurchaseDingdan){
        this->dingdan->type = Dingdan::SaleOut;
    }else if(dingdan->type == Dingdan::SaleOut){
        this->dingdan->type = Dingdan::PurchaseIn;
    }else if(dingdan->type == Dingdan::PurchaseBack){
        this->dingdan->type = Dingdan::SaleBack;
    }

    relation = this->dingdan->getUserRelation();

    if(dingdan->type == Dingdan::SaleOut || dingdan->type == Dingdan::SaleBack){
        ui->labelClientName->setText("供应商名称");
        type = 1;//我方为采购方
    }else{
        ui->labelClientName->setText("客户名称");
        type = 0;//我方为销售方
    }

    ui->lineEditClientName->setText(relation==nullptr?"":relation->nickName);
    ui->lineEditContact->setText(relation==nullptr?"":relation->contact);
    ui->lineEditTel->setText(relation==nullptr?"":relation->tel);

    ui->lineEditDingdanId->setText(dingdan->dingdanId);
    ui->dateEdit->setDate(QDate::fromString(dingdan->date, "yyyy-MM-dd"));
    ui->lineEditDingdanRemark->setText(dingdan->remark);
    ui->comboBoxTicket->setCurrentIndex(dingdan->isTicket);

    dingdanService.getImportDingdanDetails(
                this,
                dingdan->sourceUsername,
                dingdan->sourceCompanyId,
                dingdan->dingdanId,
                type);
    exec();
}

void DingdanExchangeWidget::setSelectedProduct(int index){
    sourceDetail = modelSource->getDetail(index);
    sourceProduct = modelSource->getProduct(index);
    targetDetail = modelTarget->getDetail(index);
    targetProduct = modelTarget->getProduct(index);

    ui->lineEditSourceType->setText(sourceProduct==nullptr?"":sourceProduct->type);
    ui->lineEditSourceName->setText(sourceProduct==nullptr?"":sourceProduct->name);
    ui->lineEditSourceUnit->setText(sourceProduct==nullptr?"":sourceProduct->unit);
    ui->lineEditSourceCount->setText(sourceDetail==nullptr?"0":QString("%1").arg(sourceDetail->count));

    ui->lineEditTargetType->setText(targetProduct==nullptr?"":targetProduct->type);
    ui->lineEditTargetName->setText(targetProduct==nullptr?"":targetProduct->name);
    ui->lineEditTargetUnit->setText(targetProduct==nullptr?"":targetProduct->unit);
    ui->lineEditTargetCount->setText(targetDetail==nullptr?"0":QString("%1").arg(targetDetail->count));
}

void DingdanExchangeWidget::on_pushButtonClear_clicked()
{
    if(currentRow == -1){
        return;
    }

    ui->lineEditSourceType->clear();
    ui->lineEditSourceName->clear();
    ui->lineEditSourceUnit->clear();
    ui->lineEditSourceCount->setText("0");
    modelSource->setItemForRow(currentRow, new DingdanDetail(), new Product());
    ui->tableViewSource->selectRow(currentRow);
}

void DingdanExchangeWidget::on_lineEditSourceCount_editingFinished()
{
    int count = ui->lineEditSourceCount->text().toInt();
    ui->lineEditSourceCount->setText(QString("%1").arg(count));
    modelSource->setItemCount(currentRow, count);
}

QList<HistoryProduct*> DingdanExchangeWidget::getHistoryProducts(){
    QList<HistoryProduct*> historyProducts;
    QList<DingdanDetail*> sourceDetails = modelSource->getDetails();
    QList<Product*> sourceProducts = modelSource->getProducts();
    QList<DingdanDetail*> targetDetails = modelTarget->getDetails();
    QList<Product*> targetProducts = modelTarget->getProducts();

    if(relation == nullptr){
        return historyProducts;
    }

    for(int i=0;i<sourceDetails.size();i++){
        HistoryProduct *historyProduct = new HistoryProduct();
        historyProduct->type = type;
        historyProduct->sourceCompanyId = relation->sourceCompanyId;
        historyProduct->targetCompanyId = relation->targetCompanyId;
        historyProduct->sourceProductId = sourceProducts[i]->productId;
        historyProduct->targetProductId = targetProducts[i]->productId;
        historyProduct->sourceScale = sourceDetails[i]->count;
        historyProduct->targetScale = targetDetails[i]->count;
        historyProduct->historyPrice = sourceDetails[i]->price;
        historyProducts.append(historyProduct);
    }

    return historyProducts;
}

void DingdanExchangeWidget::on_pushButtonImport_clicked()
{
    productService.updateHistoryProduct(this, getHistoryProducts(), 1);

    dingdan->details.clear();
    for(DingdanDetail* sourceDetail:modelSource->getDetails()){
        if(!sourceDetail->productId.isEmpty()){
            sourceDetail->username = dingdan->sourceUsername;
            dingdan->details.append(sourceDetail);
        }
    }

    this->close();
    emit this->importDingdanSuccess(dingdan);
}

void DingdanExchangeWidget::on_pushButtonNewProduct_clicked()
{
    newProductWidget.showWithTargetProduct(targetProduct);
}
